#Include ../Plugin.ahk
#Include ../../core/Hook.ahk

#Include DrawMgr.ahk
#Include ToolBar.ahk

#Include Types/DrawBorder.ahk
#Include Types/DrawFree.ahk
#Include Types/DrawRect.ahk
#Include Types/DrawText.ahk
#Include Types/DrawLine.ahk

class DrawPlugin extends Plugin {

  __New(dire) {
    this.dire := dire
  }

  Run() {
    Hook.Register(Events.OnDraw, DisplayDrawTool)

    DisplayDrawTool(params, *) {
      DCon(params, &mainGui, &x, &y, &w, &h)
      if mainGui.data['drawing']
        return
      mainGui.data.drawing := true
      _dire := this.dire = 'auto' ? (w > h ? 'h' : 'v') : this.dire
      cbId := Hook.Register(Events.OnDestroy, (data, *) => (data[0] = mainGui && Clean()))

      mgr := DrawMgr(x - 1, y - 1, w + 2, h + 2)
      mgr
        .Register('border', DrawBorder)
        .Register('free', DrawFree)
        .Register('rect', DrawRect)
        .Register('text', DrawText)
        .Register('line', DrawLine)

      mgr.UseHandler('border')
      mgr.BeginDraw()
      mgr.Draw()
      mgr.EndDraw()

      mgr.UseHandler('free')

      me := MouseEvent(mgr.canvas.hwnd)
      me.Register(MouseEvent.Events.LBUTTON_DOWN, OnLD)
      me.Register(MouseEvent.Events.RBUTTON_DOWN, MoveWin)

      bar := ToolBar(x - 1, y + h + 2, mgr, Clean, OnEndDraw)
      bar.Refresh()

      OnLD(*) {
        mgr.BeginDraw()
        while GetKeyState('lbutton', 'p')
          mgr.Draw(), Sleep(10)
        mgr.EndDraw()
      }

      MoveWin(*) {
        CoordMode "Mouse", "Screen"
        MouseGetPos(&px, &py), mgr.canvas.gui.GetPos(&wx, &wy)
        dx := wx - px, dy := wy - py
        While GetKeyState("RButton", "P") {
          MouseGetPos(&nx, &ny)
          if nx = px and ny = py
            continue
          mx := nx + dx, my := ny + dy
          mgr.Move(mx - 1, my - 1)
          mainGui.Move(mx, my)
          bar.Move(mx - 1, my + h + 2)
          px := nx, py := ny
        }
      }

      Clean(*) {
        mgr.Destroy(), bar.Destroy()
        mainGui.data.drawing := false
        Hook.unRegister(Events.OnDestroy, cbId)
      }

      OnEndDraw(*) {
        mainGui.GetPos(&x, &y)
        hdc_frame := GetDC(0), hdd_frame := GetDC(mainGui.Hwnd)
        BitBlt(hdd_frame, -1, -1, w, h, hdc_frame, x, y)
        ReleaseDC(hdc_frame), ReleaseDC(hdc_frame)
        Clean()
      }

    }
  }
}